import { BASE_URL } from "../../utils/config";

interface IPageData {
  userInfo: {
    userName: string;
    avatar: string;
    userStatus?: string;
    className?: string;
    loginName: string;
    hasFace: boolean;
    classesId?: string;
    faceImage: string;
  };
}

Page<IPageData>({
  data: {
    userInfo: {
      name: '',
      avatar: '/assets/icons/default-avatar.svg',
      studentId: '',
      className: '',
      phone: '',
      email: '',
      hasFace: false,
      classesId: '',
      classList: []
    }
  },

  onLoad() {
    this.fetchUserInfo();
    this.fetchClassList();
  },

  fetchClassList() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/student/classes/list`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res: any) => {
        const { data } = res.data;
        if (data) {
          this.setData({
            classList: data
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取班级列表失败',
          icon: 'error'
        });
      }
    });
  },

  fetchUserInfo() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `${BASE_URL}/user/info`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res: any) => {
        const { data } = res.data;
        if (data) {
          const matchedClass = this.data.classList.find(item => item.id === data.classesId);
          this.setData({
            userInfo: {
              userName: data.userName || '',
              avatar: data.avatar || '',
              classesId: data.classesId || '',
              className: matchedClass ? matchedClass.className : '',
              userStatus: data.userStatus || '',
              loginName: data.loginName || '',
              hasFace: data.faceImage ? true : false,
              faceImage: data.faceImage || '',
            }
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'error'
        });
      }
    });
  }
});